﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Xml;

namespace Universe.WCF.Behaviors
{
    public class TrafficPublisher
    {
        static private bool IsDone;
        static object Sync = new object();

        internal static void Publish()
        {
            if (!IsDone)
                lock(Sync)
                    if (!IsDone)
                    {
                        try
                        {
                            NetNamedPipeBinding binding = new NetNamedPipeBinding();
                            binding.ReaderQuotas = XmlDictionaryReaderQuotas.Max;
                            binding.MaxReceivedMessageSize = Int32.MaxValue;
                            ServiceHost sh = new ServiceHost(typeof (TrafficPublisherService));
                            sh.AddServiceEndpoint(typeof (ITrafficPublisher), binding, Address);
                            sh.Open();
                            IsDone = true;
                            Debug.WriteLine("ITrafficPublisher have published on " + Address);
                        }
                        catch(Exception ex)
                        {
                            Debug.WriteLine("Failed to publish ITrafficPublisher" + Environment.NewLine + ex);
                        }
                    }
        }

        static string Address
        {
            get
            {
                int id = Process.GetCurrentProcess().Id;
                return GetUri(id);
            }
        }

        public static string GetUri(int idProcess)
        {
            return
                string.Format(
                    "net.pipe://localhost/Universe.TrafficProfiler/Info/{0}",
                    idProcess);
        }
        
    }

    [ServiceContract]
    public interface ITrafficPublisher
    {
        [OperationContract]
        void Get(out TrafficStatistic onServer, out TrafficStatistic onClient);
    }

    class TrafficPublisherService: ITrafficPublisher
    {
        public void Get(out TrafficStatistic onServer, out TrafficStatistic onClient)
        {
            onServer = TrafficDefaultInfo.ServerStatistic.Clone();
            onClient = TrafficDefaultInfo.ClientStatistic.Clone();
        }
    }
}
